'use strict';

import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    Image,
    TextInput,
    TouchableHighlight,
    Dimensions
} from 'react-native';

import PropTypes from "prop-types";
import Color from "../../config/theme/standard/color";
import FontSize from "../../config/theme/standard/fonts";
import Label from '../label';

export default class SearchBar extends Component{

    constructor(props){
        super(props);
        this.state = {
            prevPropsDefaultValue : props.defaultValue ? props.defaultValue : '',
            text: this.props.defaultValue,
            placeholder: this.props.placeholder ? this.props.placeholder : "请输入关键字",
            showCancel: false,
            showCenter: true,
            hasCloseButton: this.props.hasCloseButton ? this.props.defaultValue ? false : true : false,
            isWideScreen: false // 鸿蒙适配是否宽屏
        }
    }
    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (('defaultValue' in nextProps) && (nextProps.defaultValue !== prevState.prevPropsDefaultValue)) {
            return {
                text: nextProps.defaultValue,
                prevPropsDefaultValue: nextProps.defaultValue
            };
        }
        if (('placeholder' in nextProps) && (nextProps.placeholder != prevState.placeholder)) {
            return {
                placeholder: nextProps.placeholder
            };
        }
        return null;
    }

    _onChange(text){
        this.setState({
            text:text,
        });
        if(typeof(this.props.onChange) === 'function'){
            this.props.onChange(text);
        }
    }

    _onEndEditing(text){
        if(typeof(this.props.onEndEditing) === 'function'){
            this.props.onEndEditing(this.state.text);
        }
    }

    _onSubmitEditing(text){
        if(typeof(this.props.onSubmitEditing) === 'function'){
            this.props.onSubmitEditing(this.state.text);
        }
    }

    _onFocus(){
        this.setState({
            showCancel:true,
            showCenter:false,
            hasCloseButton: this.props.hasCloseButton
        });

        if(typeof(this.props.onFocus) === 'function'){
            this.props.onFocus();
        }
    }

    _onBlur(text){
        this.setState({
            showCancel:false,
            showCenter:true,
            hasCloseButton:false
        });
        if(typeof(this.props.onBlur) === 'function'){
            this.props.onBlur(this.state.text);
        }
    }
    _onPressSpeechIcon(){
        if(typeof(this.props.onPressSpeech) === 'function'){
            this.props.onPressSpeech();
        }
    }

    _onPress(){
        if(this.props.showCancel) {
            this.textInput.blur();
            if(typeof(this.props.onPress) === 'function'){
                this.props.onPress(this.state.text);
            }
        } else {
            this.setState({
                showCancel:false,
                showCenter:true
            });
            this.textInput.blur();
            if(typeof(this.props.onPress) === 'function'){
                this.props.onPress(this.state.text);
            }
        }
    }

    clearInputValue(){
        this.setState({text:''});
        this.textInput.blur();
    }

    inputBlurEvent(){
        this.textInput.blur();
    }

    leftBackButtonEvent(){
        if(typeof(this.props.leftBackButtonEvent) === 'function'){
            this.props.leftBackButtonEvent();
        }
    }

    render() {
        const {
            title,
            titleStyle,
            showRightButton,
            showSpeechIcon,
            showLeftIcon,
            inputStyle,
            editable,
            textAlign,
            hasBackground,
            inputType,
            rightIcon,
            keyboardType,
            containerStyle,
            showLeftBackButton,
            rightFontStyle
            //hasCloseButton
        } = this.props;

        const imageStyles = [styles.image];
        const imgContainerStyles = [styles.imgContainer];
        const inputStyles = [styles.input];
        const leftIconStyles = [styles.leftIcon];
        const containerStyles = [styles.container];

        let shortWidth = Dimensions.get('window').width - 79;
        let longWidth = Dimensions.get('window').width - 32;
        let leftWidthBlur = longWidth - 15;
        let leftWidthFocus = shortWidth - 15;
        inputStyles.push({width:longWidth});
        imgContainerStyles.push({left:leftWidthBlur});

        if (inputStyle) {
            inputStyles.push(inputStyle);
        }
        if(containerStyle){
            containerStyles.push(containerStyle)
        }

        let leftBackButton = null;
        if(showLeftBackButton){
            longWidth = longWidth - 31;
            shortWidth = shortWidth - 31;
            leftWidthBlur = leftWidthBlur - 31;
            //leftWidthFocus = leftWidthFocus - 31; 
            inputStyles.push({width:longWidth,marginLeft:4})
            leftBackButton = (
                <TouchableHighlight
                    onPress ={()=>{
                        this.leftBackButtonEvent()
                    }}
                    underlayColor='transparent'
                    style={styles.imgBackContainer}
                >
                    <Image
                        source={require('../../assets/searchBar_icon_back.png')}
                        style={styles.imgBack} />
                </TouchableHighlight>
            );
        }

        let buttonItem = null;
        if(showRightButton && (this.state.showCancel || this.props.showCancel)) {
            inputStyles.push({marginRight: 14, width: shortWidth});
            imgContainerStyles.push({left: leftWidthFocus});
            buttonItem = <View>
                <TouchableHighlight
                    onPress ={()=>{
                        this._onPress();
                    }}
                    underlayColor='transparent'
                >
                    <View style={styles.labelContainer}>
                        <Label type={'secTitle'} text={title} labelStyle={[{color: Color.searchBar.rightButton,fontSize:FontSize.searchBar.rightButtonFontSize,fontWeight:'400',textAlign:'right'},titleStyle,rightFontStyle]}/>
                    </View>
                </TouchableHighlight>
            </View>;
        }

        let leftIconElement = null;
        if (showLeftIcon) {
            let img = require('../../assets/icon_searchBar.png');
            let num = this.state.placeholder.length;
            let strWidth = num * 14;
            if(this.state.showCenter && textAlign=='center' && this.state.text.length == 0){
                let left;
                if(this.props.showCancel && showRightButton){
                    left = (longWidth - strWidth)/2 - 38;
                } else {
                    left = (longWidth - strWidth)/2 - 8;
                }
                if(showLeftBackButton){
                    left = left + 33;
                }
                leftIconStyles.push({left: left});
                inputStyles.push({paddingLeft: 31, textAlign: 'center'});
            }else{
                let left = inputType == 'small' ? 12 : 27;
                if(showLeftBackButton){
                    left = left + 33;
                } 
                leftIconStyles.push({left: left});
                inputStyles.push({paddingLeft: 31, textAlign: 'left'});
                if(!showRightButton){
                    inputStyles.push({width:longWidth - 1});
                }
            };
            
            leftIconElement = (
                <Image
                    source={img}
                    style={leftIconStyles}
                />
            );
        }else {
            if(this.state.showCenter && textAlign=='center'&& this.state.text.length == 0){
                inputStyles.push({paddingLeft: 0,textAlign: 'center'});
            }else{
                inputStyles.push({paddingLeft: 16,textAlign: 'left'});
            }
        }

        if(!hasBackground){
            containerStyles.push({height: 33,backgroundColor: Color.searchBar.backgroundOff,borderRadius:16})
        }

        if(inputType == 'small'){
            inputStyles.push({flex:1, height: 33, paddingLeft: 31, paddingRight: 50,fontSize: FontSize.searchBar.smallTypeInputFontSize, backgroundColor:Color.searchBar.backgroundOff, borderRadius:16});
            imgContainerStyles.push({left: Dimensions.get('window').width - this.props.leftWidth});
            imageStyles.push({width: 36, height: 24})
        }

        let rightIconElement = null;
        let imgItem = rightIcon ? rightIcon : inputType == 'small' ? require('../../assets/icon_search_sound_small.png') : require('../../assets/icon_search_sound.png');
        if(this.state.text.length != 0 && inputType == 'normal' && this.state.hasCloseButton){
            rightIconElement = (
                <TouchableHighlight
                    onPress ={()=>{
                        this._onChange('');
                        this.textInput.focus();
                    }}
                    underlayColor='transparent'
                      style={[imgContainerStyles,{alignItems:'center',paddingRight:3}]}
                >
                    <Image
                        source={require('../../assets/icon_search_clear.png')}
                        style={styles.imgClose} />
                </TouchableHighlight>
            );
            inputStyles.push({paddingRight: 31})
        }else if(showSpeechIcon){
            rightIconElement = (
                <TouchableHighlight
                    onPress ={()=>{
                        this._onPressSpeechIcon();
                    }}
                    underlayColor='transparent'
                    style={imgContainerStyles}
                >
                    <Image
                        source={imgItem}
                        style={imageStyles} />
                </TouchableHighlight>
            );
        }

        if(this.props.inputBorderRadius) {
            inputStyles.push({borderRadius: this.props.inputBorderRadius})
        }
        if(!this.props.editable) {
            inputStyles.push({color: Color.searchBar.disable})
        }
        return (
            <View style={containerStyles}>
                {leftBackButton}
                <TextInput
                    ref={(e) => this.textInput = e}
                    style={inputStyles}
                    underlineColorAndroid='transparent'
                    editable={editable}
                    onChangeText={(text) => this._onChange(text)}
                    onBlur={(text) => this._onBlur(text)}
                    onFocus={() => this._onFocus()}
                    onEndEditing={(text) => this._onEndEditing(text)}
                    onSubmitEditing={(text) => this._onSubmitEditing(text)}
                    placeholder={this.state.placeholder}
                    value={this.state.text}
                    placeholderTextColor={inputType=='small'? Color.searchBar.placeholder :Color.searchBar.placeholder}
                    keyboardType={keyboardType}
                    returnKeyType={this.props.returnKeyType}
                    autoFocus={this.props.autoFocus}
                />
                {leftIconElement}
                {rightIconElement}
                {buttonItem}
            </View>
        );
    }
}

SearchBar.propTypes = {
    /**
     * 按钮文字
     */
    title: PropTypes.string,
    /**
     * 按钮文字
     */
    titleStyle: PropTypes.oneOfType([PropTypes.array,PropTypes.object,PropTypes.number]),
    /**
     * 按钮点击事件
     */
    onPress: PropTypes.func,
    /**
     * 暗字提示
     */
    placeholder:PropTypes.string,
    /**
     * 右边按钮
     */
    showRightButton:PropTypes.bool,
    /**
     * 获取焦点事件
     */
    onFocus : PropTypes.func,
    /**
     * 失去焦点事件
     */
    onBlur : PropTypes.func,
    /**
     * 输入框内容变化时事件
     */
    onChange : PropTypes.func,
    /**
     * 是否显示左侧图标
     */
    showLeftIcon: PropTypes.bool,
    /**
     * 是否显示语音图标
     */
    showSpeechIcon: PropTypes.bool,
    /**
     * 自定义右侧图标
     */
    rightIcon: PropTypes.any,
    /**
     * 点击语音按钮
     */
    onPressSpeech: PropTypes.func,
    /**
     * 是否可编辑
     */
    editable : PropTypes.bool,
    /**
     * 输入框样式
     */
    inputStyle : PropTypes.any,
    /**
     * 对齐方式
     */
    textAlign : PropTypes.string,
    /**
     * 是否有背景
     */
    hasBackground : PropTypes.bool,
    /**
     * 输入框类型
     */
    inputType : PropTypes.oneOf(['normal','small']),
    /**
     * 弹起键盘类型
     */
    keyboardType: PropTypes.oneOf(['default','numeric','email-address','phone-pad']),
    /**
     * 是否显示关闭按钮
     */
    hasCloseButton : PropTypes.bool,
    // 是否自动获取焦点
    autoFocus: PropTypes.bool,
    // “确定按钮”实际显示的内容
    returnKeyType: PropTypes.any,
    // 输入框圆角大小
    inputBorderRadius: PropTypes.number,
    // 编辑完毕调用的方法
    onEndEditing: PropTypes.func,
    // 软件盘的确定/提交按下时调用
    onSubmitEditing: PropTypes.func,
    // 默认值
    defaultValue: PropTypes.string,
    // 是否直接展示右侧按钮
    showCancel: PropTypes.bool,
    //外部容器样式
    containerStyle:PropTypes.any,
    //是否显示左侧返回按钮
    showLeftBackButton: PropTypes.bool,
    //左侧返回按钮点击事件
    leftBackButtonEvent: PropTypes.func,
    //rightButton
    rightFontStyle:PropTypes.any,
};

SearchBar.defaultProps = {
    title: "",
    showRightButton: true,
    editable: true,
    showSpeechIcon: true,
    showLeftIcon: true,
    textAlign: 'center',
    hasBackground: true,
    inputType: 'normal',
    keyboardType: "default",
    hasCloseButton: true,
    autoFocus: false,
    returnKeyType: 'done',
    inputBorderRadius: 16,
    defaultValue: '',
    showCancel: false,
    showLeftBackButton: false,
    leftWidth:200
};

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        height:44,
        backgroundColor: Color.searchBar.background,
        justifyContent:'center'
    },
    input: {
        fontSize: FontSize.searchBar.inputFontSize,
        paddingRight: 31,
        paddingLeft: 4,
        width: 115,
        height: 33,
        backgroundColor : Color.searchBar.backgroundOff,
        borderRadius: 16,
        paddingTop: 0,
        paddingBottom: 0,
        color: Color.searchBar.input,
        fontWeight:'400'
    },
    image: {
        width: 28,
        height: 28,
        resizeMode:'contain'
    },
    leftIcon: {
        width: 16,
        height: 16,
        position:'absolute',
        left: 27,
        zIndex: 10,
        resizeMode:'contain'
    },
    imgContainer:{
        position: 'absolute',
        zIndex: 10,
        width:28,
        height:28,
        justifyContent: 'center',
    },
    labelContainer:{
        height: 22,
        alignItems: 'center',
        justifyContent: 'center',
    },
    imgClose: {
        width: 28,
        height: 28,
        resizeMode:'contain'
    },
    imgBack:{
        width: 20,
        height: 20,
        resizeMode:'contain'
    },
    imgBackContainer:{
        marginLeft: 4,
        marginRight: 7
    }
});
